/*
 * GameManager.cpp
 *
 *  Created on: 27/07/2010
 *      Author: alex
 */

#include <SDL/SDL.h>
#include <SDL/SDL_ttf.h>
#include <SDL/SDL_mixer.h>
#include <SDL/SDL_framerate.h>
#include <cstdlib>
#include "states/SplashState.h"
#include "states/ArenaState.h"
#include "states/EndState.h"
#include "core/utils.h"
#include "InputManager.h"
#include "GameManager.h"

using namespace utils;


GameManager::GameManager(int frameRate) :
timer(1), dt(1) {
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO);
	Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024);
	TTF_Init();
	manex = (FPSmanager*) malloc(sizeof(FPSmanager));
	SDL_initFramerate(manex);
	SDL_setFramerate(manex, frameRate);
	screen = SDL_SetVideoMode(VIDEO_WIDTH, VIDEO_HEIGHT, VIDEO_BPP, SDL_HWSURFACE);
	state = new SplashState();
}


GameManager::~GameManager() {
	delete state;
	free(manex);
	TTF_Quit();
	Mix_CloseAudio();
	SDL_Quit();
}


void GameManager::run() {
	unsigned t1 = SDL_GetTicks();
	while ( ! inputManager.pollEvents().isQuitRequested() ) {
		state->update(dt).render(screen);
		if (state->hasFinished()) changeState(state->getNext());
		SDL_Flip(screen);
		SDL_framerateDelay(manex);
		timer = t1;
		t1 = SDL_GetTicks();
		dt = t1 - timer;
	}
}


void GameManager::changeState(StateType next) {
	delete state;
	switch (next) {
	case STATE_SPLASH:
		state = new SplashState();
		break;
	case STATE_ARENA:
		state = new ArenaState();
		break;
	case STATE_END:
		state = new EndState();
		break;
	}
}
